/**
 * xxxxxxx
 * xxxxxx
 * xxxxxxx
 */
import { useState, useRef, useEffect} from 'react'

export function useWebsocket({ url }) {
    const ws = useRef(null);
    const [readyState, setReadyState] = useState({ key: 0, value: '正在连接中' })
    const [messageData, setMessageData] = useState(undefined)
  
    const webSocketInit = () => {
      if (!ws.current || ws.current.readyState === 3) {
        createWebSocket()
      }
    };
    /**
     * 创建
     */
    const createWebSocket = () => {
      try {
        const readyStateArr = [
          { key: 0, value: '正在连接中' },
          { key: 1, value: '已经连接并且可以通讯' },
          { key: 2, value: '连接正在关闭' },
          { key: 3, value: '连接已关闭或者没有连接成功' }
        ]
  
        ws.current = new WebSocket(url)
  
        ws.current.onopen = (evt) => {
          setReadyState(readyStateArr[ws.current?.readyState ?? 0])
        }
        ws.current.onclose = (evt) => setReadyState(readyStateArr[ws.current?.readyState ?? 0])
        ws.current.onmessage = (evt) => {
          setMessageData(evt.data)
        }
        ws.current.onerror = (evt) => setReadyState(readyStateArr[ws.current?.readyState ?? 0])
  
      } catch (error) {
        console.log(error)
      }
    }
  
    /**
     * 关闭
     */
    const closeWebSocket = () => {
      ws.current?.close()
    }
  
    /**
     * 重连
     */
    const reconnect = () => {
      try {
        closeWebSocket()
        ws.current = null
        createWebSocket()
      } catch (e) {
        console.log(e)
      }
    }
  
    const sendMessage = (msg) => {
      if (!ws.current || ws.current.readyState !== 1) {
        return;
      }
      console.log('sendMsg',msg)
      console.log(ws.current.send)
      ws.current.send(msg)
    }
  
    useEffect(() => {
      webSocketInit()
      return () => {
        ws.current?.close()
      }
    }, [ws])
  
  
    return {
      readyState,
      closeWebSocket,
      reconnect,
      sendMessage,
      messageData
    }
  }